package cn.edu.tsinghua.cic.ccss.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.forten.core.ro.DtoResultWithPageInfo;
import org.forten.utils.system.LogUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import cn.edu.tsinghua.cic.ccss.bo.CadreBo;
import cn.edu.tsinghua.cic.ccss.bo.CourseBo;
import cn.edu.tsinghua.cic.ccss.bo.CourseSelectBo;
import cn.edu.tsinghua.cic.ccss.bo.CoursewareBo;
import cn.edu.tsinghua.cic.ccss.dto.CadreDto;
import cn.edu.tsinghua.cic.ccss.dto.CourseDto;
import cn.edu.tsinghua.cic.ccss.dto.CourseSelectionDto;
import cn.edu.tsinghua.cic.ccss.dto.CoursewareDto;
import cn.edu.tsinghua.cic.ccss.qo.CourseSelectCadreQo;

/**个人选课Controller
 * @author cj
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("selectcourse")
@SessionAttributes({ "courseSelectCadreQo" })
public class CourseAction4SelectionCadre extends SuperAction {
	private static Logger log = Logger
			.getLogger(CourseAction4SelectionCadre.class);

	@Resource(name = "courseSelectCadreQo")
	private CourseSelectCadreQo courseSelectCadreQo;
	@Resource(name = "courseSelectBo")
	private CourseSelectBo courseSelectBo;
	@Resource(name = "courseBo")
	private CourseBo courseBo;
	@Resource(name = "cadreBo")
	private CadreBo cadreBo;
	@Resource(name = "coursewareBo")
	private CoursewareBo coursewareBo;

	private String message = null;

	@RequestMapping("gotoCourseSelectionCadre")
	public String gotoCourseSelectionCadre(Model model) {

		model.addAttribute("courseSelectCadreQo", courseSelectCadreQo);
		return "forward:showCourseSelectionCadreList.jspx";
	}

	@RequestMapping("showCourseSelectionCadreList")
	public String showCourseSelectionCadre(
			Model model,
			@RequestParam(defaultValue = "1") int pageNo,
			@ModelAttribute("courseSelectCadreQo") CourseSelectCadreQo courseSelectCadreQo) {
		int[] total = this.cadreBo.getCreditInfo(getLoginCardNum());
		int max = total[0];
		int currentCredit = total[1];
		int sub = total[2];
		int nextCredit = total[3];
		int nextSub = total[4];
		
		Long cadreId = this.courseSelectBo.getIdByCardNum(getLoginCardNum());
		if (cadreId == 0) {
			return "403";
		}
		CadreDto cadreDto = cadreBo.loadCadreDto(cadreId);
		DtoResultWithPageInfo<CourseDto> dtoList = this.courseBo
				.queryCourseDtoPage(courseSelectCadreQo, pageNo,"teachTime",false);
		List<CourseDto> result = (List<CourseDto>) dtoList.getResults();
		List<CourseSelectionDto> dto = this.courseSelectBo
				.queryCoursesForThisStudent(cadreId);
		List<CourseDto> willRemoveList = new ArrayList<CourseDto>();
		for (CourseSelectionDto csDto : dto) {
			CourseDto cDto = csDto.getCourseDto();
			willRemoveList.add(cDto);
		}
		result.removeAll(willRemoveList);
		model.addAttribute("dto_chosen", dto);
		model.addAttribute("cadreNum", cadreDto.getCardNum());
		model.addAttribute("cadreName", cadreDto.getName());
		model.addAttribute("cadreId", cadreId);
		model.addAttribute("courseSelectCadreQo", courseSelectCadreQo);
		model.addAttribute("dto_choose", result);
		model.addAttribute("page", dtoList.getPageInfo());
		model.addAttribute("max", max);
		model.addAttribute("currentCredit", currentCredit);
		model.addAttribute("sub", sub);
		model.addAttribute("nextCredit", nextCredit);
		model.addAttribute("nextSub", nextSub);
		return "selectcourse/grxkList";
	}

	@RequestMapping("selectCourse")
	public String selectCourse(Model model, @RequestParam Long courseId,
			@RequestParam Long cadreId) {
		boolean isOverMaxCredit = this.courseSelectBo.isOverMaxCredit(cadreId,
				courseId);
		boolean isOverMaxStudents = this.courseSelectBo
				.isOverMaxStudents(courseId);
		boolean isOverTime = this.courseSelectBo.isOverTime(courseId);
		if (isOverMaxCredit) {
			message = "您所修的学分已达上限";
			model.addAttribute("message", message);
			LogUtil.warn(log, message);
			return "forward:showCourseSelectionCadreList.jspx";
		} else if (isOverMaxStudents) {
			message = "该课程选课人数已满";
			model.addAttribute("message", message);
			LogUtil.warn(log, message);
			return "forward:showCourseSelectionCadreList.jspx";
		} else if(isOverTime){
			message = "该课程已停止选课";
			model.addAttribute("message", message);
			LogUtil.warn(log, message);
			return "forward:showCourseSelectionCadreList.jspx";
		}
			else {
			courseSelectBo.selectCourse4Cadre(cadreId, getLoginCardNum(),
					courseId);
			message = "操作成功";
			List<CourseSelectionDto> dto = this.courseSelectBo
					.queryCoursesForThisStudent(cadreId);
			model.addAttribute("message", message);
			model.addAttribute("dto_chosen", dto);
			return "forward:showCourseSelectionCadreList.jspx";
		}
	}

	@RequestMapping("cancelCourseByCadre")
	public String cancelCourse(Model model,
			@RequestParam Long selectedCourseId,
			@RequestParam String cancelReason) {
		boolean isEnableCancelCourse = this.courseSelectBo
				.isEnableCancelCourse(selectedCourseId);
		if (isEnableCancelCourse) {
			this.courseSelectBo.cancelCourse(selectedCourseId, cancelReason);
			message = "退课成功！";
			List<CourseSelectionDto> dtoSelect = this.courseSelectBo
					.queryCoursesForThisStudent(courseSelectBo
							.getIdByCardNum(getLoginCardNum()));
			model.addAttribute("dto_chosen", dtoSelect);
			model.addAttribute("message", message);
		} else {
			message = "该课程不能退！有需要请联系系统管理员";
			model.addAttribute("message", message);
		}
		return "forward:gotoCourseSelectionCadre.jspx";
	}

	@RequestMapping("leave")
	public String leave(Model model, @RequestParam String leaveReason,
			@RequestParam Long selectedCourseId) {
		this.courseSelectBo.leave4Cadre(selectedCourseId, leaveReason);
		message = "请假成功!";
		model.addAttribute("message", message);
		return "forward:gotoCourseSelectionCadre.jspx";
	}
	
	@RequestMapping("gotoDownloadCourseware")
	public String gotoDownloadCourseware(Model model,
			@RequestParam(defaultValue = "") Long courseId){
		List<CoursewareDto> dtos = coursewareBo.findCoursewareByCourseId(courseId);
		CourseDto courseDto = courseBo.loadCourseDto(courseId);
		model.addAttribute("courseDto", courseDto);
		model.addAttribute("dtos", dtos);
		return "courseware/kjxz";
	}
	
	@RequestMapping("downloadCourseware")
	public void downloadCourseware(@RequestParam(defaultValue = "") Long id,
			HttpServletRequest request, HttpServletResponse response) throws IOException{
		byte[] courseware = coursewareBo.downloadCoursewareById(id,response);
		
		ServletOutputStream out = response.getOutputStream();
		out.write(courseware);
		out.flush();
		out.close();
	}

}
